﻿using UnityEngine;
using System.Collections;
using System.Text;

public class stg222 : MonoBehaviour
{
    stg2_cardScript card = new stg2_cardScript();
    public Texture2D fruit_btn;
    public Texture2D animal_btn;
    public static int[] mixCardNum = new int[11];
    public static int[] mixCardNum1 = new int[11];
    private int[] testWord = new int[6];
    public static int problem_manager;  //카드의 tag번호
    public static int game_type;

    bool isTop = false;
    bool select_btn1 = false;
    bool select_btn2 = false;
    public static float top, bot;

    public Camera MainCamera;
    RaycastHit hitObj;
    GameObject mouse_g;
    Vector3 mouseVector;

    int k = 1;
    int problem_num = 5;        //총 문제수
    private static int select_answer;          //몇번째 버튼을 클릭했는가
    int problem_count = 0;      //몇번째문제 푸는중인가
    private static int answer_count = 0;
    bool outKey = false;
    private static bool select_on = false;
    private static bool test_on = false;
    bool btn, btn1, btn2, btn3, btn4;
    private static bool isFinish = false;

    char[,] store_array = new char[11, 11];
    string apple = "apple", grape = "grape", orange = "orange";
    string melon = "melon", strawberry = "strawberry", pear = "pear";
    string peach = "peach", watermelon = "watermelon", kiwi = "kiwi", banana = "banana";

    string cow = "COW", panda = "PANDA", pig = "PIG";
    string mouse = "MOUSE", tiger = "TIGER", deer = "DEER";
    string bear = "BEAR", rabbit = "RABBIT", monkey = "MONKEY", lion = "LION";


    string state1 = "";
    string state2 = "";
    string state3 = "";
    string state4 = "";

    public GUITexture backgroundImage;
    //public KinectWrapper.NuiSkeletonPositionIndex TrackedJoint = KinectWrapper.NuiSkeletonPositionIndex.HandRight;
    public GameObject OverlayObject;
    public float smoothFactor = 100f;

    public GUIText debugText;
    private float distanceToCamera = 10f;
    public static float cur_x, cur_y, cur_z;
    float touch_z = 0, touch_y = 0;
    private bool progressDisplayed = false;
    int result_s2;

    public enum STATE { INIT, STAGE, TEST_SETTING, TEST_MODE, CHECK, CLEAR_PROBLEM, IDLE, FINISH }
    public static STATE state = STATE.INIT;

    // Use this for initialization
    void Start()
    {
        mouse_g = GameObject.Find("mouse");
        if (OverlayObject)
        {
            distanceToCamera = (OverlayObject.transform.position - Camera.main.transform.position).magnitude;
        }
    }

    // Update is called once per frame
    void Update()
    {
        /*KinectManager manager = KinectManager.Instance;

        if (manager && manager.IsInitialized())
        {
            if (backgroundImage && (backgroundImage.texture == null))
            {
                backgroundImage.texture = manager.GetUsersClrTex();
            }

            int iJointIndex = (int)TrackedJoint;

            if (manager.IsUserDetected())
            {
                uint userId = manager.GetPlayer1ID();

                if (manager.IsJointTracked(userId, iJointIndex))
                {
                    Vector3 posJoint = manager.GetRawSkeletonJointPos(userId, iJointIndex);

                    if (posJoint != Vector3.zero)
                    {


                        // 3d position to depth
                        Vector3 posDepth = manager.GetDepthMapPosForJointPos(posJoint);

                        // depth pos to color pos
                        Vector2 posColor = manager.GetColorMapPosForDepthPos(posDepth);

                        cur_x = (float)posColor.x / KinectWrapper.Constants.ColorImageWidth;
                        cur_y = 1.0f - (float)posColor.y / KinectWrapper.Constants.ColorImageHeight;
                        cur_z = posDepth.z;

                        if (debugText)
                        {

                            debugText.guiText.text = "coordinate: " + cur_x.ToString() + ',' + cur_y.ToString() + ',' + posDepth.z.ToString();
                        }

                        if (OverlayObject)
                        {
                            Vector3 vPosOverlay = Camera.main.ViewportToWorldPoint(new Vector3(cur_x, cur_y, distanceToCamera));
                            OverlayObject.transform.position = Vector3.Lerp(OverlayObject.transform.position, vPosOverlay, smoothFactor * Time.deltaTime);
                        }

                    }
                }

            }

        }*/
        switch (state)
        {
            case STATE.STAGE:
                StartCoroutine("MakeStage2");
                break;
            case STATE.TEST_SETTING:
                test_setting();
                break;
            case STATE.TEST_MODE:
                StartCoroutine("make_test");
                break;
            case STATE.CHECK:
                test_check();
                break;
            case STATE.CLEAR_PROBLEM:
                clear_problem();
                break;
            case STATE.FINISH:
                finish();
                break;

        }
        GUITexture mouse = mouse_g.guiTexture;

        mouseVector.x = mouse.GetScreenRect().x + mouse.GetScreenRect().width / 2;
        mouseVector.y = mouse.GetScreenRect().y + mouse.GetScreenRect().height / 2;

        Ray ray = MainCamera.ScreenPointToRay(mouseVector);

        if (Physics.Raycast(ray, out hitObj, Mathf.Infinity))
        {

        }

    }

    public void click()
    {
        if (cur_x > 0.82 && cur_x < 0.93 && cur_y > 0.86 && cur_y < 0.91)
        {
            clear();
            DestroyObject(GameObject.FindWithTag("test"));
            DestroyObject(GameObject.FindWithTag("MainCamera"));
            Application.LoadLevel("mainMenu");
        }
        if (state == STATE.INIT)
        {
            if (cur_x > 0.16 && cur_x < 0.28 && cur_y > 0.53 && cur_y < 0.78)
            {
                select_btn1 = true;
                game_type = 1;
                result_s2 = eduProgramClient.Instance.msgHandle("STAGE 2.1 Start");
                state = STATE.STAGE;
                select_on = true;
            }
            else if (cur_x > 0.41 && cur_x < 0.53 && cur_y > 0.53 && cur_y < 0.78)
            {
                select_btn2 = true;
                game_type = 2;
                result_s2 = eduProgramClient.Instance.msgHandle("CHECK");
                Debug.Log("551 Not Permit");
                if (result_s2 != 551)
                {
                    state = STATE.STAGE;
                    select_on = true;
                }
            }
        }
        else if (state == STATE.IDLE && test_on == false)
        {
            if (cur_y > 0.4)
            {
                isTop = true;
                top = 0.82f;
                bot = 0.55f;
            }
            else
            {
                isTop = false;
                top = 0.3f;
                bot = 0.03f;
            }
            if (cur_x > 0.08 && cur_x < 0.20 && cur_y > bot && cur_y < top)
            {
                if (isTop)
                {
                    var oil = GameObject.FindWithTag("CARD10");
                    oil.animation.Play("wordTouch");
                    if (game_type == 1)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/fruit10");
                        oil.audio.PlayOneShot(ac);
                    }
                    else if (game_type == 2)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/animal10");
                        oil.audio.PlayOneShot(ac);
                    }
                }
                else
                {
                    var oil = GameObject.FindWithTag("CARD5");
                    oil.animation.Play("wordTouch");
                    if (game_type == 1)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/fruit5");
                        oil.audio.PlayOneShot(ac);
                    }
                    else if (game_type == 2)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/animal5");
                        oil.audio.PlayOneShot(ac);
                    }
                }
            }
            else if (cur_x > 0.22 && cur_x < 0.34 && cur_y > bot && cur_y < top)
            {
                if (isTop)
                {
                    var oil = GameObject.FindWithTag("CARD1");
                    oil.animation.Play("wordTouch");
                    if (game_type == 1)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/fruit1");
                        oil.audio.PlayOneShot(ac);
                    }
                    else if (game_type == 2)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/animal1");
                        oil.audio.PlayOneShot(ac);
                    }
                }
                else
                {
                    var oil = GameObject.FindWithTag("CARD6");
                    oil.animation.Play("wordTouch");
                    if (game_type == 1)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/fruit6");
                        oil.audio.PlayOneShot(ac);
                    }
                    else if (game_type == 2)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/animal6");
                        oil.audio.PlayOneShot(ac);
                    }
                }
            }
            else if (cur_x > 0.36 && cur_x < 0.49 && cur_y > bot && cur_y < top)
            {
                if (isTop)
                {
                    var oil = GameObject.FindWithTag("CARD2");
                    oil.animation.Play("wordTouch");
                    if (game_type == 1)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/fruit2");
                        oil.audio.PlayOneShot(ac);
                    }
                    else if (game_type == 2)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/animal2");
                        oil.audio.PlayOneShot(ac);
                    }
                }
                else
                {
                    var oil = GameObject.FindWithTag("CARD7");
                    oil.animation.Play("wordTouch");
                    if (game_type == 1)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/fruit7");
                        oil.audio.PlayOneShot(ac);
                    }
                    else if (game_type == 2)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/animal7");
                        oil.audio.PlayOneShot(ac);
                    }
                }
            }
            else if (cur_x > 0.51 && cur_x < 0.63 && cur_y > bot && cur_y < top)
            {
                if (isTop)
                {
                    var oil = GameObject.FindWithTag("CARD3");
                    oil.animation.Play("wordTouch");
                    if (game_type == 1)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/fruit3");
                        oil.audio.PlayOneShot(ac);
                    }
                    else if (game_type == 2)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/animal3");
                        oil.audio.PlayOneShot(ac);
                    }
                }
                else
                {
                    var oil = GameObject.FindWithTag("CARD8");
                    oil.animation.Play("wordTouch");
                    if (game_type == 1)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/fruit8");
                        oil.audio.PlayOneShot(ac);
                    }
                    else if (game_type == 2)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/animal8");
                        oil.audio.PlayOneShot(ac);
                    }
                }
            }
            else if (cur_x > 0.65 && cur_x < 0.78 && cur_y > bot && cur_y < top)
            {
                if (isTop)
                {
                    var oil = GameObject.FindWithTag("CARD4");
                    oil.animation.Play("wordTouch");
                    if (game_type == 1)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/fruit4");
                        oil.audio.PlayOneShot(ac);
                    }
                    else if (game_type == 2)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/animal4");
                        oil.audio.PlayOneShot(ac);
                    }
                }
                else
                {
                    var oil = GameObject.FindWithTag("CARD9");
                    oil.animation.Play("wordTouch");
                    if (game_type == 1)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/fruit9");
                        oil.audio.PlayOneShot(ac);
                    }
                    else if (game_type == 2)
                    {
                        var ac = (AudioClip)Resources.Load("Sound Files/animal9");
                        oil.audio.PlayOneShot(ac);
                    }
                }
            }
            else if (cur_x > 0.69 && cur_x < 0.80 && cur_y > 0.86 && cur_y < 0.91)
            {
                clear();
                answer_count = 0;
                isFinish = false;
                test_on = true;
                state = STATE.TEST_SETTING;
            }

        }
        else if (test_on)
        {
            if (cur_x > 0.06 && cur_x < 0.17 && cur_y > 0.43 && cur_y < 0.50)
            {
                btn1 = true;
                select_answer = 1;
                print(select_answer);
                state = STATE.CHECK;
            }
            if (cur_x > 0.21 && cur_x < 0.32 && cur_y > 0.43 && cur_y < 0.50)
            {
                btn2 = true;
                select_answer = 2;
                print(select_answer);
                state = STATE.CHECK;
            }
            if (cur_x > 0.36 && cur_x < 0.47 && cur_y > 0.43 && cur_y < 0.50)
            {
                btn3 = true;
                select_answer = 3;
                print(select_answer);
                state = STATE.CHECK;
            }
            if (cur_x > 0.51 && cur_x < 0.62 && cur_y > 0.43 && cur_y < 0.50)
            {
                btn4 = true;
                select_answer = 4;
                print(select_answer);
                state = STATE.CHECK;
            }
        }

    }

    void insertArray(int j, string a)
    {
        for (int i = 0; i < a.Length; i++)
        {
            store_array[j, i] = a.ToCharArray()[i];
        }
    }

    void mixCard()
    {
        for (var i = 1; i <= 10; i++)
        {
            mixCardNum[i] = k;      //카드 번호 순서대로 넣기
            k += 2;
        }
        k = 1;

        /*for (var i = 1; i <= 10; i++)
        {
            var n1 = Random.Range(1, 8);   //1-16까지 랜덤하게 선택
            var n2 = Random.Range(1, 8);

            var j = mixCardNum[n1];
            mixCardNum[n1] = mixCardNum[n2];
            mixCardNum[n2] = j;
        }*/
    }

    void mixCard1()
    {
        for (var i = 1; i <= 10; i++)
        {
            mixCardNum1[i] = k;      //카드 번호 순서대로 넣기
            k += 1;
        }
        k = 1;

        for (var i = 1; i <= 15; i++)
        {
            var n1 = Random.Range(1, 10);   //1-16까지 랜덤하게 선택
            var n2 = Random.Range(1, 10);

            var j = mixCardNum1[n1];
            mixCardNum1[n1] = mixCardNum1[n2];
            mixCardNum1[n2] = j;
        }
    }

    IEnumerator MakeStage2()     //StartCoroutine사용시 반드시 IEnumerator 사용
    {
        state = STATE.IDLE;
        mixCard();

        var x = -7.5f;
        var y = 3.0f;
        for (var i = 1; i <= 10; i++)
        {
            var card = Resources.Load("Prefabs/word_card") as GameObject;    //prefabs로 카드 생성
            Instantiate(card, new Vector3(x, y, 5), transform.rotation);   //카드 위치 지정
            card.gameObject.tag = "CARD" + ((mixCardNum[i] / 2) + 1);   //오브젝트에 tag 설정
            x += 3f;
            if (i % 5 == 0)
            {      //줄 바꿈
                x = -7.5f;
                y -= 5f;
            }
            yield return new WaitForSeconds(0.025f);    //0.25초 간격으로 카드 배열
        }
    }

    void test_setting()
    {
        state = STATE.IDLE;
        mixCard();
        if (game_type == 1)
        {
            insertArray(1, apple);
            insertArray(2, grape);
            insertArray(3, orange);
            insertArray(4, melon);
            insertArray(5, strawberry);
            insertArray(6, pear);
            insertArray(7, peach);
            insertArray(8, watermelon);
            insertArray(9, kiwi);
            insertArray(10, banana);
        }
        else if (game_type == 2)
        {
            insertArray(1, cow);
            insertArray(2, panda);
            insertArray(3, pig);
            insertArray(4, mouse);
            insertArray(5, tiger);
            insertArray(6, deer);
            insertArray(7, bear);
            insertArray(8, rabbit);
            insertArray(9, monkey);
            insertArray(10, lion);
        }



        for (var i = 1; i <= problem_num; i++)
        {
            testWord[i] = mixCardNum[i];
        }
        state = STATE.TEST_MODE;
    }

    IEnumerator make_test()
    {

        state = STATE.IDLE;
        if (problem_count == problem_num)
        {
            state = STATE.FINISH;
        }

        if (state == STATE.IDLE)
        {
            problem_count++;
            var card = Resources.Load("Prefabs/word_test") as GameObject;   //그림생성
            Instantiate(card, new Vector3(0, 3.0f, 5), transform.rotation);
            card.gameObject.tag = "CARD" + testWord[problem_count];
            yield return new WaitForSeconds(1.0f);
            int problem_manger1 = (problem_manager / 2) + 1;

            while (!outKey)     //사지선다 섞기
            {
                mixCard1();
                for (var temp = 1; temp < problem_num; temp++)
                {
                    if (mixCardNum1[temp] == problem_manger1)     //섞인거에 그림에 해당하는 답이있으면 while문나가기
                    {
                        outKey = true;
                    }
                }
            }

            for (int i = 1; i <= 4; i++)
            {        //보기 4개
                int n = mixCardNum1[i];
                for (int k = 0; k < 11; k++)
                {
                    if (store_array[n, k] != null)
                    {
                        if (i == 1)
                        {
                            state1 += store_array[n, k].ToString();
                        }
                        if (i == 2)
                        {
                            state2 += store_array[n, k].ToString();
                        }
                        if (i == 3)
                        {
                            state3 += store_array[n, k].ToString();
                        }
                        if (i == 4)
                        {
                            state4 += store_array[n, k].ToString();
                        }
                    }
                }
            }
        }
    }

    void test_check()
    {
        state = STATE.IDLE;
        int problem_manger1 = (problem_manager / 2) + 1;
        switch (select_answer)
        {
            case 1:
                if (mixCardNum1[1] == problem_manger1) answer_count++;
                else print(false);
                break;
            case 2:
                if (mixCardNum1[2] == problem_manger1) answer_count++;
                else print(false);
                break;
            case 3:
                if (mixCardNum1[3] == problem_manger1) answer_count++;
                else print(false);
                break;
            case 4:
                if (mixCardNum1[4] == problem_manger1) answer_count++;
                else print(false);
                break;
        }
        state = STATE.CLEAR_PROBLEM;
    }

    void clear_problem()
    {
        state = STATE.IDLE;
        //stg2_wordTest.problem_script = 1;       //초기화
        btn1 = false;
        btn2 = false;
        btn3 = false;
        btn4 = false;
        outKey = false;
        state1 = "";
        state2 = "";
        state3 = "";
        state4 = "";
        clear();
        state = STATE.TEST_MODE;
    }

    void finish()
    {
        if (answer_count >= 3)
            eduProgramClient.Instance.msgHandle("STAGE 2.1 Finish");
        else
            eduProgramClient.Instance.msgHandle("STAGE 2.1 Fail");
        state = STATE.IDLE;
        clear();
        btn = false;
        test_on = false;
        problem_count = 0;
        isFinish = true;
    }

    void OnGUI()
    {
        var quit_btn = GUI.Button(new Rect(800, 30, 130, 50), "Go To Main!");
        if (quit_btn)
        {
            DestroyObject(GameObject.FindWithTag("test"));
            DestroyObject(GameObject.FindWithTag("MainCamera"));
            Application.LoadLevel("mainMenu");
        }
        if (state == STATE.INIT)
        {
            select_btn1 = GUI.Button(new Rect(150, 100, 130, 130), fruit_btn);
            select_btn2 = GUI.Button(new Rect(400, 100, 130, 130), animal_btn);

        }

        if (select_on)
        {
            btn = GUI.Button(new Rect(670, 30, 130, 50), "TEST!");
            if (btn)
            {
                clear();
                test_on = true;
                state = STATE.TEST_SETTING;
            }
        }


        if (test_on)
        {
            btn1 = GUI.Button(new Rect(50, 240, 130, 50), "" + state1);
            btn2 = GUI.Button(new Rect(200, 240, 130, 50), "" + state2);
            btn3 = GUI.Button(new Rect(350, 240, 130, 50), "" + state3);
            btn4 = GUI.Button(new Rect(500, 240, 130, 50), "" + state4);
            if (btn1)
            {
                select_answer = 1;
                state = STATE.CHECK;
            }
            if (btn2)
            {
                select_answer = 2;
                state = STATE.CHECK;
            }
            if (btn3)
            {
                select_answer = 3;
                state = STATE.CHECK;
            }
            if (btn4)
            {
                select_answer = 4;
                state = STATE.CHECK;
            }
        }

        if (isFinish)
        {
            GUIStyle style = new GUIStyle();
            style.fontSize = 20;
            style.normal.textColor = Color.black;
            string stringToEdit = "Number of total problems : " + problem_num;
            string stringToEdit1 = "Number of correct problems : " + answer_count;
            GUI.Label(new Rect(500, 100, 130, 50), stringToEdit, style);
            GUI.Label(new Rect(500, 200, 130, 50), stringToEdit1, style);
        }
    }

    void clear()
    {
        for (var i = 1; i < 20; i++)
        {
            var obj = GameObject.FindWithTag("CARD" + i);   //tag로 오브젝트 탐색
            Destroy(obj);
        }
    }
}